package com.highspeed.bdk.gateway.socket.analyze.preset.deploy.request.issued.instruction;

import com.highspeed.bdk.gateway.Util;
import com.highspeed.bdk.gateway.socket.analyze.preset.deploy.request.issued.base.InstructionType;

import java.text.SimpleDateFormat;
import java.util.Date;

public class AppInstruction {

    /**
     * @param content 预置信息
     * @return
     */
    public byte[] createIssuedInstruction(InstructionType instructionType, byte[] content, short srcLogicalId, short destLogicalId, String version) {
        int len = content.length + 70;
        byte[] bytes = new byte[len];
        int offset = 0;
        //帧头
        Util.putInt(bytes, 0x55555555, offset);
        offset += 4;

        //消息长度
        Util.putInt(bytes, len, offset);
        offset += 4;

        //源逻辑ID
        Util.putShort(bytes, srcLogicalId, offset);
        offset += 2;

        //目的逻辑ID
        Util.putShort(bytes, destLogicalId, offset);
        offset += 2;

        //消息类型
        Util.putByte(bytes, (byte) 0x20, offset);
        offset += 1;

        //消息类别
        Util.putByte(bytes, (byte) 0xF0, offset);
        offset += 1;

        //消息ID
        Util.putShort(bytes, instructionType.getMessageId(), offset);
        offset += 2;

        //消息发送时间
        Date date = new Date();
        long second = date.getTime() / 1000;
        Util.putInt(bytes, (int) second, offset);
        offset += 4;

        Util.putInt(bytes, 0, offset);
        offset += 4;

        //消息发送序号，默认1
        Util.putShort(bytes, (short) 1, offset);
        offset += 2;

        //保留,默认0，6个字节
        offset += 6;

        //命令编号,暂时不填
        offset += 20;

        //预置表编号，暂时不填
        offset += 2;

        //预置表版本号
        String[] versions = version.split("\\.");
        for (int i = 0; i < versions.length; i++) {
            String str = versions[i];
            offset += Util.stringToBCD(bytes, offset, str);
        }

        //保留，暂时不填
//        Util.putByte(bytes, (byte) 0, offset);
        offset += 1;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        String time = simpleDateFormat.format(new Date());
        for (String t : time.split("-")) {
            //固话时间
            offset += Util.stringToBCD(bytes, offset, t);
        }

        //保留，暂时不填
//        Util.putByte(bytes, (byte) 1, offset);
        offset += 1;

        //预置	信息，不定长
        for (int i = 0; i < content.length; i++) {
            bytes[offset++] = content[i];
        }
        Util.putInt(bytes, 0xAAAAAAAA, offset);
        offset += 4;
        return bytes;
    }

}
